package component

import (
	"bytes"
	"encoding/json"
	"github.com/duke-git/lancet/v2/random"
)

func RandStr(length int) string {

	return random.RandNumeralOrLetter(length)
}

func JsonEncode(v any) (bytes []byte, err error) {
	bytes, err = json.Marshal(v)

	return
}

func JsonDecode(data []byte, v any) (err error) {
	err = json.Unmarshal(data, v)
	return
}

func SliceIndex[T comparable](s []T, x T) int {
	for i, v := range s {
		if v == x {
			return i
		}
	}
	return -1
}

func SliceDelete[T comparable](s []T, x T) []T {
	for i, v := range s {
		if v == x {
			s = append(s[:i], s[i+1:]...)
			break
		}
	}
	return s
}

func BinaryStr(data []byte) string {
	var buf bytes.Buffer
	for _, b := range data {
		for i := 7; i >= 0; i-- {
			if b&(1<<i) != 0 {
				buf.WriteByte('1')
			} else {
				buf.WriteByte('0')
			}
		}
		buf.WriteByte(' ')
	}
	return buf.String()
}
